package com.qf.gateway.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;

@Component
public class NacosDynamicRouteService implements ApplicationEventPublisherAware {
    /**
     * 定义获取nacos上的配置信息的dateId和group
     */
    private String dateId="gateway-router";
    private String group="DEFAULT_GROUP";
    /**
     * 获取nacos的地址信息
     *
     */
    @Value("{spring.cloud.nacos.config.server-addr}")
    private String serverAddr;
    /**
     * 写路由信息的对象
     */
    @Autowired
    private RouteDefinitionWriter routeDefinitionWriter;
    /**
     * 应用配置信息的发布者
     */
    private ApplicationEventPublisher applicationEventPublisher;
    /**
     * 保存路由信息的容器
     */
    private static final List<String> ROUTE_LIST=new ArrayList<>();
    /**
     *ApplicationEventPublisherAware需要实现的方法
     * @param applicationEventPublisher 回调一个应用配置信息发布者
     */
    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher=applicationEventPublisher;
    }
    /**
     * 清空路由
     */
    private void clearRoute(){
        for (String id: ROUTE_LIST){
            //Mono基于WebFlux模型的一个视图控制组件
            this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
        }
        ROUTE_LIST.clear();
    }
    /**
     * 添加路由
     */
    private void addRoute(RouteDefinition routeDefinition){
        routeDefinitionWriter.save(Mono.just(routeDefinition)).subscribe();
        ROUTE_LIST.add(routeDefinition.getId());
    }
    /**
     *  用用配置信息发布
     */
    public void publish(){
        applicationEventPublisher.publishEvent(new RefreshRoutesEvent(routeDefinitionWriter));
    }
    /**
     * 从nacos上动态获取路由信息
     */
    @PostConstruct
    public void dynamicRouteByNacosListener(){
        try {
            //获取nacos配置服务
            ConfigService configService= NacosFactory.createConfigService(serverAddr);
            //路由配置信息
            String config=configService.getConfig(dateId,group, 500);
            //清空原有的路由信息
            clearRoute();
            List<RouteDefinition> gatewayRouteDefinitions= JSONObject.parseArray(config,RouteDefinition.class);
            //把解析出来的路由信息添加到本地网关路由信息中
            for (RouteDefinition routeDefinition:gatewayRouteDefinitions){
                //添加路由信息
                addRoute(routeDefinition);
            }
            //发布新的路由信息
            publish();
            //监听逻辑
            configService.addListener(dateId, group, new Listener() {
                @Override
                public Executor getExecutor() {

                    return null;
                }

                @Override
                public void receiveConfigInfo(String s) {
                    //清空原有的路由信息
                    clearRoute();
                    List<RouteDefinition> gatewayRouteDefinitions= JSONObject.parseArray(config,RouteDefinition.class);
                    //把解析出来的路由信息添加到本地网关路由信息中
                    for (RouteDefinition routeDefinition:gatewayRouteDefinitions){
                        //添加路由信息
                        addRoute(routeDefinition);
                    }
                    //发布新的路由信息
                    publish();
                }
            });

        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
}
